<template>
    <!-- <el-input v-model="formData.parentId"/> -->
    <el-tree-select v-model="selectedShelfId" :data="shelfData" :render-after-expand="false" :default-expand-all="true"
        :check-strictly="true" @change="change" />
    <!-- render-after-expand 是否在第一次展开某个树节点后才渲染其子节点
            check-strictly 在显示复选框的情况下，是否严格的遵循父子不互相关联的做法 -->
</template>
<script setup lang="ts">
import { ref, onMounted, watch } from "vue"
import { warehouseApi } from "@/api";

// 定义modelValue 的属性
const props = defineProps({
    modelValue: { type: Number, default: 0 },
    disabled: { type: Boolean, default: false }
})

// 数据流向是单向的，从父到子
// 定义触发器 defineEmits  声明 可以从子到父，提前给父亲声明，等会要用到你的money
const emit = defineEmits(['update:modelValue'])


const selectedShelfId = ref(0)
const shelfData = ref([])
onMounted(() => {
    selectedShelfId.value = props.modelValue
    callShelfApi()
})
watch(() => props.modelValue, (newVal, oldVal) => {
    // console.log(newVal);
    selectedShelfId.value = newVal

})
const change = (val: number) => {
    emit("update:modelValue", val)
    selectedShelfId.value = val
}
const callShelfApi = () => {
    warehouseApi.select.call().then((res: any) => {
        // console.log(res);

        res.forEach((item: any) => {
            item.value = item.id
            item.label = item.name
            item.disabled = props.disabled
        });

        let shelfData2 = res.reduce((duzi: any, currentValue: any) => {
            currentValue.children = res.filter((item: any) => item.parentId === currentValue.id)
            if (currentValue.parentId === 0) {
                duzi.push(currentValue)
            }
            return duzi
        }, [])

        if(props.disabled){
            shelfData.value = shelfData2
        }else{
        shelfData.value = [{ value: 0, label: "选择库位" }].concat(shelfData2)
    }
    })
}
</script>